setScreenMetrics(device.width, device.height);

app_func = {
    appName: "趣头条",
    packageName: 'com.jifen.qukan',
    mainActivity: 'com.jifen.qkbase.main.MainActivity',
    videoActivity: "com.jifen.qkbase.main.MainActivity",
    taskInfo: null,
    coin: 0,
    bounds: {
        task_button: null,
        video_button: null
    },
    sleepTime: 5 * 1000,
    lastrewardTime: null,
    thread: null,
    stopflag: null,
    finish: false
}

let current_package = "com.jifen.qukan";
function launchAppEnhance(app_name) {
    let result;
    let thread = threads.start(function () {
        toastLog("检查是否有打开权限!");
        trytimes = 3
        while (trytimes > 0) {
            trytimes--
            var allow = text("允许").findOne(3000);
            if (allow) {
                sleep(1000)
                toastLog("发现允许授权!");
                allow.click();
                thread.interrupt();
                break;
            }
        }
    });
    sleep(1000);
    if (currentPackage() != current_package) {
        result = launchApp(app_name);
        sleep(3000);
    }
    else {
        result = currentPackage();
    }
    thread.interrupt();
    return result;
}

function find_task_button(str) {
    var task_button = null;
    for (var i = 0; i < 3; i++) {
        task_button = textStartsWith(str).findOne(5000);
        if (task_button) {
            app_func.bounds.task_button = task_button.bounds()
            return 0;
        }
        else {
            toastLog("没找到" + str);
            // 关广告  各种返回到首页
            clean_obs()
            continue;
        }
    }

    return -1;
}

function find_video_button(str) {
    var target_button = null;
    for (var i = 0; i < 3; i++) {
        var target_button = find_button_by_textStartsWith(str);
        if (target_button) {
            toastLog("控件text:", target_button.text());
            app_func.bounds.video_button = target_button.bounds()
            return 0;
        }
        else {
            toastLog("没找到视频界面");
            // 关广告  各种返回到首页
            clean_obs()
            continue;
        }
    }

    return -1;
}

// 点击控件坐标，控件的clickbale为false的时候
function 点击控件(x) {
    var weight = x.bounds()
    click(weight.centerX(), weight.centerY())
}

//关闭各种弹窗广告
function close_all_ad() {
    try { text('我知道了').findOne(500).click(); } catch (e) { }
    try { text('跳过').findOne(500).click(); } catch (e) { }
    try { text('禁止').findOne(500).click(); } catch (e) { }
    try { text('以后再说').findOne(500).click(); } catch (e) { }
    try { text('取消').findOne(500).click(); } catch (e) { }
    //////////////////////////////////////////////////////////
    try {
        var 我知道了 = text('我知道了').findOne(500)
        if (我知道了) {
            点击控件(我知道了)
        }
    } catch (error) {
    }

    try { //图片弹窗
        let 弹窗 = textStartsWith('直接退出').findOne(500)
        if (弹窗 && !is_mainAct()) {
            click_button(弹窗.bounds())
            toastLog("0")
        }
    } catch (e) { }

    try { text('知道了').findOne(500).click(); } catch (e) { }

    try { //领取金币
        let 领50金币 = id('com.jifen.qukan:id/bei').findOne(500) ||
            id('com.jifen.qukan:id/a6a').findOne(500) ||
            textStartsWith("领50金币").findOne(500) ||
            id('com.jifen.qukan:id/a70').findOne(500) ||
            id('com.jifen.qukan:id/a6z').findOne(500)
        if (领50金币) {
            click_button(领50金币.bounds())
            sleep(2000)
            if (currentActivity() != 'com.jifen.qkbase.main.MainActivity') {
                close_time_adv()
            }
            toastLog("1")
        }
    } catch (e) { }

    try { //营销
        let 营销 = id('ag7').findOne(500)
        if (营销) {
            营销.click()
            toastLog("2")
        }
    } catch (e) { }

    try { //阅读收益
        let 阅读收益 = text('阅读收益').findOne(500)
        if (阅读收益) {
            back()
            toastLog("3")
        }
    } catch (e) { }

}

//清除各种障碍 直到主界面
function clean_obs() {
    var result = null

    if (is_mainAct()) {
        //关闭各种广告
        close_all_ad()
        result = 0
    }
    else {
        //存在是在主页 也有弹窗
        result = err_back()
    }
    return result
}

function is_mainAct() {
    sleep(1000)
    var curact = currentActivity();
    if (curact != app_func.mainActivity) {
        toastLog("不在主界面")
        return false
    }
    else {
        toastLog("当前是主界面")
        return true
    }
}

function is_yaoqianAct() {
    sleep(1000)
    var curact = currentActivity();
    if (curact != "com.jifen.qkbase.web.WebActivity") {
        toastLog("不在摇钱树")
        return false
    }
    else {
        toastLog("当前在摇钱树")
        return true
    }
}

function err_back() {
    var curact = null;
    for (var i = 0; i < 3; i++) {
        curact = currentActivity()
        sleep(1000)
        if (curact != app_func.mainActivity) {
            toastLog("尝试回到主界面")
            back();
            sleep(3000)
        }
        else {
            toastLog("已回到当前主界面")
            break
        }
    }

    if (curact != app_func.mainActivity) {
        toastLog("回主界面失败")
        return -1
    }

    return 0
}

function find_button_by_text(textstr) {
    toastLog("寻找按钮:" + textstr);
    var task_button = null
    for (var i = 0; i < 2; i++) {
        task_button = text(textstr).findOne(3000);
        if (task_button) {
            console.log("找到控件text:", task_button.text());
            break;
        }
        else {
            console.log("第" + (i + 1) + "次未找到");
            close_all_ad()
            continue;
        }
    }

    return task_button
}

function find_button_by_textStartsWith(textstr) {
    toastLog("寻找按钮:" + textstr);
    var task_button = null
    for (var i = 0; i < 1; i++) {
        task_button = textStartsWith(textstr).findOne(1000);
        if (task_button) {
            console.log("找到控件text:", task_button.text());
            break;
        }
        else {
            console.log("第" + (i + 1) + "次未找到");
            close_all_ad()
            continue;
        }
    }
    return task_button
}

//传入坐标参数
function click_button(bounds) {
    toastLog("点击按钮:" + bounds.centerX() + bounds.centerY());
    sleep(1000);
    click(bounds.centerX(), bounds.centerY());
    sleep(2000)
}

//寻找img类型关闭按钮
function find_X_adv_button() {
    //点击下载出现的时候   倒计时控件不存在的时候
    var close = className("android.widget.ImageView").depth("5").indexInParent("1").findOne(2000) || className("android.widget.ImageView").depth("1").indexInParent("1").findOne(2000)
        || id("tt_video_ad_close_layout").findOne(2000)
    var 倒计时 = id("b").depth("5").indexInParent("3").findOne(2000)
    if (close && !倒计时) {
        toastLog("发现关闭按钮");
        sleep(1000);
        click_button(close.bounds());
        //点快了
        继续观看 = find_button_by_textStartsWith("继续观看")
        if (继续观看) {
            click_button(继续观看.bounds())
            return -1
        }
        else {
            return 0
        }
    }
    else {
        //内嵌广告三件套
        //弹支付宝   取消安装   关闭按钮
        try {
            取消 = textStartsWith("取消").findOne(500)
            if (取消) {
                click_button(取消.bounds())
                toastLog("11")
            }
        } catch (error) {
        }
        try {
            关闭 = textStartsWith("关闭").findOne(500)
            if (关闭) {
                click_button(关闭.bounds())
                toastLog("22")
            }
        } catch (error) {
        }
        try {//支付宝
            if (currentPackage() != app_func.packageName) {
                sleep(2000)
                back()
                sleep(2000)
                继续 = textStartsWith("继续").findOne(2000)
                toastLog("33")
                if (继续) {
                    click_button(继续.bounds())
                    toastLog("44")
                }
            }
        } catch (error) {
        }
        return -1
    }
}

//寻找text类型关闭按钮
function find_close_adv_button() {
    toastLog("开始寻找关闭广告按钮------------------:");
    var target_button = text("关闭广告").findOne(2 * 1000);
    if (target_button) {
        toastLog("控件text:", target_button.text());
        click_button(target_button.bounds())
        //点快了
        继续观看 = find_button_by_textStartsWith("继续观看")
        if (继续观看) {
            click_button(继续观看.bounds())
            return -1
        }
        else {
            return 0
        }
    }
    else {
        toastLog("没找到关闭广告按钮");
        return -1;
    }
}

//寻找 没有倒计时存在后  back
function find_end_state_button() {
    var task_button = text("点击重播").findOne(3000) || text('立即领取').findOne(2000)
    if (task_button) {
        toastLog("发现点击重播");
        back()
        return 0
    }
    else {
        //寻找关闭按钮 //倒计时按钮
        关闭 = find_button_by_textStartsWith("关闭")
        if (关闭) {
            if (!is_mainAct()) {
                back()
                //点快了
                继续观看 = find_button_by_textStartsWith("继续观看")
                if (继续观看) {
                    click_button(继续观看.bounds())
                    return -1
                }
                else {
                    return 0
                }
            }
        }
        else {
            toastLog("没找到关闭广告按钮");
            return -1;
        }
    }
}


//处理倒计时广告
function close_time_adv() {
    //总时间为 广告时间X单次寻找等待时间
    let 广告时间 = 30
    for (var i = 0; i < 广告时间; i++) {
        sleep(1000)
        //每5秒检查一次关闭按钮是否出现
        if ((i + 1) % 5 == 0) {
            //寻找时间到的线索
            if (find_end_state_button() >= 0 ||
                find_X_adv_button() >= 0) {

                继续观看 = find_button_by_textStartsWith("继续观看")
                if (继续观看) {
                    click_button(继续观看.bounds())
                    continue
                }
            }
            if (is_mainAct() || is_yaoqianAct()) { //任务act 也应该视为广告已不存在
                return 0
            }
        }
    }
    return -1;
}

//向下滑
function _down_move(speed) {
    var truespeed = 200
    if (speed) {
        truespeed = speed
    }
    console.log("向下滑动")
    let x = device.width / 2
        , t = device.height * 4 / 5
        , b = device.height * 1 / 5
    sml_move(x, b, x, t, truespeed + random(50, 100));
    sleep(1000);
}
//向上滑
function _up_move(speed) {
    var truespeed = 200
    if (speed) {
        truespeed = speed
    }
    console.log("向上滑动")
    let x = device.width / 2
        , t = device.height * 1 / 5
        , b = device.height * 4 / 5
    sml_move(x, b, x, t, truespeed + random(50, 100));
    sleep(1000);
}

//向左滑
function _left_move(speed) {
    var truespeed = 200
    if (speed) {
        truespeed = speed
    }
    console.log("向左滑动")
    let y = device.height / 2
        , t = device.width * 1 / 5
        , b = device.width * 4 / 5
    sml_move(b, y, t, y, truespeed + random(50, 100));
    sleep(1000);
}

//向右滑
function _rigth_move(speed) {
    var truespeed = 200
    if (speed) {
        truespeed = speed
    }
    console.log("向右滑动")
    let y = device.height / 2
        , t = device.width * 4 / 5
        , b = device.width * 1 / 5
    sml_move(b, y, t, y, truespeed + random(50, 100));
    sleep(1000);
}

function sml_move(qx, qy, zx, zy, time) {
    //仿真随机带曲线滑动: qx, qy, zx, zy, time 代表起点x,起点y,终点x,终点y,过程耗时单位毫秒
    var xxy = [time];
    var point = [
        { "x": qx, "y": qy },
        { "x": random(qx - 100, qx + 100), "y": random(qy, qy + 50) },
        { "x": random(zx - 100, zx + 100), "y": random(zy, zy + 50) },
        { "x": zx, "y": zy }
    ];
    for (let i = 0; i < 1; i += 0.08) {
        xxyy = [parseInt(bezier_curves(point, i).x), parseInt(bezier_curves(point, i).y)]
        xxy.push(xxyy);
    }
    gesture.apply(null, xxy);
}

function bezier_curves(cp, t) {
    cx = 3.0 * (cp[1].x - cp[0].x);
    bx = 3.0 * (cp[2].x - cp[1].x) - cx;
    ax = cp[3].x - cp[0].x - cx - bx;
    cy = 3.0 * (cp[1].y - cp[0].y);
    by = 3.0 * (cp[2].y - cp[1].y) - cy;
    ay = cp[3].y - cp[0].y - cy - by;

    tSquared = t * t;
    tCubed = tSquared * t;
    result = { "x": 0, "y": 0 };
    result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
    result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
    return result;
};

//自动调整按钮位置并点击  适用于在屏幕外无法点击的按钮
function auto_find_button(textstr) {
    var targetbutton = find_button_by_textStartsWith(textstr)
    var trytimes = 2
    if (targetbutton) {
        toastLog("device.width:" + device.width + "device.height:" + device.height)
        toastLog("x:" + targetbutton.bounds().centerX() + "y:" + targetbutton.bounds().centerY())
        //至少把空间拖到 屏幕 device.height * 1/5   至  device.height * 4/5 之间
        while (targetbutton.bounds().centerY() > device.height * 4 / 5) {
            var uptimes = Math.ceil((targetbutton.bounds().centerY() - device.height * 4 / 5) / (device.height * 4 / 5 - device.height * 1 / 5))
            toastLog("需要滑动调整位置次数:" + uptimes)
            for (var i = 0; i < uptimes; i++) {
                _up_move()
                sleep(2000)
            }
            targetbutton = find_button_by_textStartsWith(textstr)
            trytimes--
            if (trytimes <= 0) {
                if (targetbutton) {
                    toastLog("找到按钮:" + textstr)
                }
                else {
                    toastLog("没找到按钮:" + textstr)
                }
                break
            }
        }

        while (targetbutton.bounds().centerY() < device.height) {
            var uptimes = Math.ceil((device.height * 1 / 5 - targetbutton.bounds().centerY()) / (device.height * 4 / 5 - device.height * 1 / 5))
            toastLog("需要滑动调整位置次数:" + uptimes)
            for (var i = 0; i < uptimes; i++) {
                _down_move()
                sleep(2000)
            }
            targetbutton = find_button_by_textStartsWith(textstr)
            trytimes--
            if (trytimes <= 0) {
                if (targetbutton) {
                    toastLog("找到按钮:" + textstr)
                }
                else {
                    toastLog("没找到按钮:" + textstr)
                }
                break
            }
        }

        targetbutton = find_button_by_textStartsWith(textstr)
        if (targetbutton) {
            toastLog("找到按钮:" + textstr)
        }
        else {
            toastLog("没找到按钮:" + textstr)
        }
    }
    return targetbutton
}

//签到任务
function handle_sign_task() {
    //进入任务界面 自动签到
    sleep(2000)
    let 任务坐标 = app_func.bounds.task_button
    if (任务坐标) {
        click_button(任务坐标)
        //自动签到   弹窗 看视频再领
        sleep(app_func.sleepTime)
        handle_more_reward_task()

        let 签到按钮 = find_button_by_textStartsWith("明日签到")
        if (签到按钮) {
            //说明已签到
            close_all_ad()
        }
        else {
            toastLog("签到状态不确定")
        }

        toastLog("签到任务完成")
        return 0
    }
    else {
        toastLog("没找到任务界面")
        err_handle()
        return -1
    }
}


//开宝箱任务
function open_baoxiang() {
    toastLog("开宝箱")
    click_button(app_func.bounds.task_button)
    //通过领取后变倒计时那个控件来判断宝箱是否可点 id bne
    var baoxiang = textEndsWith("金币").id("bn8").findOne(5000) || textEndsWith("金币").id("fj").findOne(1000)
    if (baoxiang) {
        click_button(baoxiang.bounds());
        close_time_adv()
        return 0
    }
    else {
        toastLog("没有发现宝箱");
        return -1
    }
}

//摇树任务
function yaoshu_task() {
    toastLog("摇树任务")
    click_button(app_func.bounds.task_button)
    for (var i = 0; i < 3; i++) {
        摇钱树领金币 = textStartsWith("摇钱树领金币").findOne(1000)
        if (摇钱树领金币) {
            break
        }
        else {
            _up_move(800)
            continue
        }
    }

    if (摇钱树领金币) {
        click_button(摇钱树领金币.bounds())
        摇钱树领金币2 = textStartsWith("摇钱树领金币").findOne(1000)
        if (摇钱树领金币2) {
            click_button(摇钱树领金币2.bounds())
        }
        //再点一次，有些版本需要点两次
        sleep(3000)
    }
    else {
        toastLog("没找到摇钱树领金币")
        err_back()
        return -1
    }
    sleep(app_func.sleepTime)
    您还有 = textStartsWith("您还有").findOne(5000)
    if (您还有) {
        几次 = 您还有.parent().child(3)
        执行次数 = 几次.text()
        if (执行次数) {
            for (var i = 0; i < 执行次数; i++) {
                领金币 = textStartsWith("领").findOne(2000)
                if (领金币) {
                    click_button(领金币.bounds())
                    close_time_adv()
                }
                else {
                    toastLog("没有找到领取按钮")
                    err_back()
                    return -1
                }
            }
        }
        else {
            toastLog("没找到可执行次数")
            err_back()
            return -1
        }
    }
    else {
        toastLog("没找到您还有按钮")
        err_back()
        return -1
    }

    err_back()
    return 0
}


//走路任务
function walk_task() {
    toastLog("走路任务")
    走路赚钱 = find_button_by_textStartsWith("走路赚钱")
    if (走路赚钱) {
        click_button(走路赚钱.bounds())
        var jiangli = ["视频奖励", "签到奖励"]
        for (var i = 0; i < jiangli.length; i++) {
            var 按钮 = find_button_by_textStartsWith(jiangli[i])
            while (按钮) {
                close_all_ad()
                click_button(按钮.bounds())
                close_time_adv()
                close_all_ad()
                按钮 = find_button_by_textStartsWith(jiangli[i])
            }
        }

        var 偷步数 = className("android.view.View").depth("14").indexInParent("3").findOne(2000)
        if (偷步数) {
            click_button(偷步数.bounds())
            //偷三次
            close_all_ad()
        }
    }
    else {
        toastLog("没有找到走路赚钱")
        return -1
    }

    err_back()
    return 0
}

//睡觉任务
function sleep_task() {
    toastLog("睡觉任务")
    var date = new Date();
    var h = date.getHours();

    if (h >= 20 || h <= 7) {
        click_button(app_func.bounds.task_button)
        睡觉赚金币 = auto_find_button("睡觉赚金币")
        if (睡觉赚金币) {
            click_button(睡觉赚金币.bounds())
        }
        else {
            toastLog("没找到睡觉赚金币")
            err_back()
            return -1
        }

        var 开始睡觉 = find_button_by_textStartsWith("开始睡觉")
        if (开始睡觉) {
            click_button(开始睡觉.bounds())
        }
        else {
            toastLog("可能已经睡了")
        }

    }
    else {
        toastLog("没到睡觉时间")
    }
    if (h >= 8 && h <= 19) {
        click_button(app_func.bounds.task_button)
        睡觉赚金币 = auto_find_button("睡觉赚金币")
        if (睡觉赚金币) {
            click_button(睡觉赚金币.bounds())
        }
        else {
            toastLog("没找到睡觉赚金币")
            err_back()
            return -1
        }

        var 我醒来啦 = find_button_by_textStartsWith("我醒来啦")
        if (我醒来啦) {
            click_button(我醒来啦.bounds())
            let 领取金币 = find_button_by_textStartsWith("领取金币")
            if (领取金币) {
                click_button(领取金币.bounds())
                let 立即收下 = find_button_by_textStartsWith("立即收下")
                if (立即收下) {
                    click_button(立即收下.bounds())
                }
                else {
                    toastLog("没找到立即收下")
                    err_back()
                    return -1
                }
            }
            else {
                toastLog("没找到领取金币")
                err_back()
                return -1
            }
        }
        else if (领取金币2 = find_button_by_textStartsWith("领取金币")) {
            click_button(领取金币2.bounds())
            let 立即收下2 = find_button_by_textStartsWith("立即收下")
            if (立即收下2) {
                click_button(立即收下2.bounds())
            }
            else {
                toastLog("没找到立即收下")
                err_back()
                return -1
            }
        }
        else {
            toastLog("已点我睡醒任务或者没找到")
        }
    }

    err_back()
    //返回弹出 幸运红包   直接退出 立即领取depth 14  直接退出
    return 0
}

function handle_watch_ad_task() {
    toastLog("开始做看广告任务");
    sleep(2000)
    let 任务坐标 = app_func.bounds.task_button
    if (任务坐标) {
        click_button(app_func.bounds.task_button)
    }
    else {
        toastLog("没找到任务界面")
        err_handle()
        return -1
    }

    let 看视频领金币 = textStartsWith('看视频领金币').find()
    if (看视频领金币.length > 0) {
        for (var i = 0; i < 看视频领金币.length; i++) {
            领金币 = 看视频领金币[i]
            if (领金币) {
                click_button(领金币.bounds())
                close_time_adv()
            }
            else {
                toastLog("看视频领金币失败")
                return -1
            }
        }
    }

    return 0
}

//看视频任务
function handle_watch_video_task() {
    toastLog("开始做看视频任务");
    sleep(2000)
    //下半部分找
    let 小视频 = textStartsWith("小视频").boundsInside(0, device.height * 0.5, device.width, device.height).findOne(3000)
    if (小视频) {
        app_func.bounds.video_button = 小视频.bounds()
        click_button(app_func.bounds.video_button)
    }
    else {
        toastLog("没找小视频界面")
        err_handle()
        return -1
    }

    //60分钟至少赚5000金币

    return handle_watch_task_by_move(60 * 60 * 1000)
}

//头条页面领取金币
function lingjinbi() {
    toastLog("开始领金币任务");
    sleep(2000)
    let 头条 = textStartsWith("头条").findOne(2000)
    if (头条) {
        click_button(头条.bounds())
        sleep(2000)
        领取 = text("领取").findOne(2000)
        if (领取) {
            click_button(领取.bounds())
        }
        再领 = textStartsWith("再领").findOne(2000)
        if (再领) {
            click_button(再领.bounds())
            close_time_adv()
        }
    }
    else {
        toastLog("没找到头条界面")
        err_handle()
        return -1
    }

    //60分钟至少赚5000金币

    return 0
}

function handle_chengjiu_task() {
    toastLog("开始进入成就殿堂")

    for (var i = 0; i < 3; i++) {
        var 我的 = id("tv_tab_name").text("我的").findOne(2000)
        if (我的) {
            click_button(我的.bounds())
            var 成就殿堂 = text("成就殿堂").findOne(2000)
            if (成就殿堂) {
                click_button(成就殿堂.bounds())
                var 领取按钮 = null
                var trytimes = 3
                while (true) {
                    //没有  领取控件了   可以继续领取
                    //          领取按钮 = text( "领取").depth( "14").findOne(3000)
                    领取按钮 = text("领取").findOne(3000)
                    trytimes--
                    if (trytimes == 0) {
                        return -1
                    }
                    if (领取按钮) {
                        click_button(领取按钮.bounds())
                        close_time_adv()
                        //继续领取徽章奖励   领取奖励
                        close_all_ad()
                    }
                    else {
                        toastLog("没有可领取成就奖励")
                        return 0
                    }
                }
            }
            else {
                toastLog("没有找到成就殿堂")
                close_all_ad()
            }
        }
        else {
            toastLog("没有找到'我的'界面")
            close_all_ad()
        }
    }
    return -1
}

//提现处理
function handle_withdraw() {
    toastLog("开始提现任务")
    for (var i = 0; i < 3; i++) {
        let 我的 = id("tv_tab_name").text("我的").findOne(2000)
        if (我的) {
            click_button(我的.bounds())
            let 去提现 = text("去提现").findOne(2000)
            if (去提现) {
                //新增提现帮助提示需要关闭 点击每日可提
                click_button(去提现.bounds())
                每日可提 = text("每日可提").findOne(2000)
                if (每日可提) {
                    click_button(每日可提.bounds())
                }
                else {
                    toastLog("没找到每日可提")
                    close_all_ad()
                    continue
                }
                var 立即提现 = text("立即提现").findOne(2000)
                if (立即提现) {
                    click_button(立即提现.bounds())
                    //再一次点击立即提现  进入time广告  领取提现奖励
                    立即提现2 = text("立即提现").findOne(2000)
                    click_button(立即提现2.bounds())
                    close_time_adv()
                    close_all_ad()
                    back() //返回
                    return 0
                }
            }
            else {
                toastLog("没有找到去提现")
                //有先弹倒计时广告的情况
                close_time_adv()
                close_all_ad()  //直接领取到达 成就界面
            }
        }
        else {
            toastLog("没有找到'我的'界面")
            clean_obs()
        }
    }
    back() //返回
    return -1
}

//滑动看视频
function handle_watch_task_by_move(time) {

    let 视频坐标 = app_func.bounds.video_button
    if (视频坐标) {
        click_button(视频坐标)
    }
    else {
        toastLog("视频坐标获取失败")
        return -1
    }
    var index = 0;
    //15秒一次
    var count = parseInt(time / 1000 / 15)
    var random_min = 1000
    var random_max = 10000

    toastLog("即将滑动" + count + "次！");
    if (count == 0) {
        return 0
    }

    for (var i = 0; i < 3; i++) {
        if (is_videoAct()) {
            while (index <= count) {
                var random_time = random(random_min, random_max);
                toastLog("观看" + app_func.appName + "第" + index + "/" + count + "个视频中...");
                toastLog("预计时长" + (random_time / 1000) + "秒~");
                sleep(random_time);
                index++;
                handle_during_watch_video()
                _up_move(800)
                close_all_ad()
                err_back()
            }
            toastLog("观看结束")
            return 0
        }
        else {
            toastLog("不在视频页面")
            close_all_ad()
            let 视频坐标 = app_func.bounds.video_button
            if (视频坐标) {
                click_button(视频坐标)
            }
        }
    }
    return -1
}

function handle_during_watch_video() {
    //暂不领取
    try { textStartsWith('暂不领取').findOne(500).click(); } catch (e) { }
    //砸金蛋
    try {
        let 阅读奖励 = id("azj").findOne(500) || id("b0h").findOne(500)
        if (阅读奖励) {
            click_button(阅读奖励.bounds())
            //如果有我知道了 就没有双倍任务
            我知道了 = find_button_by_textStartsWith("我知道了")
            if (我知道了) {
                click_button(我知道了.bounds())
            }
            else {
                handle_more_reward_task()
                close_all_ad()
            }

            return 0
        }
    } catch (e) { }
}

function is_videoAct() {
    sleep(1000)
    var curact = currentActivity();
    if (curact != app_func.videoActivity) {
        toastLog("不在视频界面")
        return false
    }
    else {
        toastLog("当前是视频")
        return true
    }
}

function is_guaguaAct() {
    sleep(1000)
    var curact = currentActivity();
    if (curact != app_func.guaguaActivity) {
        toastLog("不在刮刮界面")
        return false
    }
    else {
        toastLog("当前是刮刮页面")
        return true
    }
}

//领取任务
function handle_get_task(taskstr) {
    toastLog("处理领取任务");
    sleep(2000)
    //先处理广告
    err_handle()
    for (var i = 0; i < 2; i++) {
        var target_button = find_button_by_textStartsWith(taskstr)
        if (target_button) {
            if (taskstr == "点击领取" || taskstr == "幸运抽奖" || taskstr == "神秘大礼") {
                click_button(target_button.parent().bounds())
                handle_more_reward_task()
                //开心收下    恭喜获得
                close_all_ad()
                return 1
                //点击频率过快
            }
            else {
                click_button(target_button.bounds())
                err_handle()
            }
            break
        }
        else {
            toastLog(taskstr + "按钮未找到")
            err_handle()
        }
    }

    return 0
}

//处理获得更多奖励的流程
function handle_more_reward_task() {
    toastLog("处理双倍任务");
    sleep(2000)
    //签到成功触发看视频再奖励按钮
    var strlist = ["看视频再领"]
    var target_button = null
    for (var i = 0; i < strlist.length; i++) {
        target_button = find_button_by_textStartsWith(strlist[i])
        if (target_button) {
            toastLog(target_button.text())
            break;
        }
    }
    if (target_button) {
        click_button(target_button.bounds())
        if (close_time_adv() >= 0) {
            toastLog("处理双倍任务完成")
            close_all_ad()
        }
        else {
            toastLog("处理双倍任务失败")
            close_all_ad()
            return -1
        }
    }
    else {
        //看视频再奖励流程失败
        toastLog("没找到双倍任务按钮");
        return -1
    }
    return 0
}

//线程处理关闭广告
function thread_close_all_ad() {
    var runtimes = 0
    app_func.thread = threads.start(function () {
        toastLog("启用关闭弹窗线程")
        while (!app_func.taskEnd) {
            sleep(5000)
            close_all_ad()
            runtimes++
        }
        app_func.thread.interrupt();
        toastLog("退出弹窗处理线程")
    })
    return
}

function err_handle() {
    //会有弹窗广告
    if (!is_mainAct()) {
        close_all_ad()
        close_time_adv()
    }
    else {
        close_all_ad()
    }
}

function timehandle() {
    sleep(2000)
    for (var i = 0; i < 2; i++) {
        var 首页 = find_button_by_textStartsWith("首页")
        if (首页) {
            click_button(首页.bounds())
        }
        else {
            toastLog("首页按钮寻找失败")
            err_handle()
        }
    }

    let 兑换 = id("tv_main_exchange").findOne(5000)
    if (兑换) {
        click_button(兑换.bounds())
    }
    else {
        toastLog("没找到兑换")
    }

    var date = new Date();
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();

    //点击进入 兑换界面 
    //7点30前报名  100万中级场 1000万金币高级场
    //我的金币是多少？ 
    var shoplevel = null
    var shopbutton = null
    var 我的金币 = id("tv_exchange_center_attend_not_gold").findOne(3000)
    if (我的金币) {
        var intmoney = parseInt(我的金币.text())
        if (intmoney > 10000000) {
            shoplevel = "高级兑换场"
        }
        else if (intmoney > 1000000) {
            shoplevel = "中级兑换场"
        }
        else if (intmoney > 100000) {
            shoplevel = "低级兑换场"
        }
        else {
            toastLog("金币不足参加活动" + intmoney)
            back()
            return -1
        }

        shopbutton = find_button_by_textStartsWith(shoplevel)
        if (shopbutton) {
            click_button(shopbutton.bounds())
            let 报名 = find_button_by_textStartsWith("报名" + shoplevel)
            if (报名) {
                click_button(报名.bounds())
            }
            else {
                toastLog("没找到报名按钮 ")
                // back()
                return -1
            }
            let 确认报名 = find_button_by_textStartsWith("确认报名")
            if (确认报名) {
                click_button(确认报名.bounds())
            }

            if (textContains("已经抢过了").findOne(5000)) {
                close_all_ad()
                back()
                return -1
            }
        }
        else {
            toastLog("可能已经报过名了,等待8点兑换")
        }
    }
    else {
        toastLog("没找到我的金币")
        let 兑换场 = find_button_by_textStartsWith("兑换场")
        if (兑换场) {
            toastLog("加载失败")
            return -1
        }
    }
    //如果 在 com.liziyuedong.goldpig.ui.activity.ExchangeActivity 说明已经报名   

    // 20 点抢红包
    if (h >= 20) {
        var 现金红包 = textEndsWith("现金红包").findOne(3000)
        if (现金红包) {
            let 按钮 = 现金红包.parent().child(2)
            if (按钮) {
                click_button(按钮.bounds())
            }
            else {
                toastLog("没有找到现金红包兑换按钮")
            }
        }
        else {
            toastLogtoastLog("没有找到现金红包按钮")
        }
    }
    return 0
}

function thread_handle() {
    let thread = threads.start(function () {
        toastLog("检查提示升级")
        trytimes = 3
        while (trytimes > 0) {
            trytimes--;
            var widget = text("以后更新").findOne(5000);
            if (widget) {
                widget.click();
            }
            toastLog("检查用户协议")
            widget = text("同意并进入").findOne(5000);
            if (widget) {
                widget.click();
            }
            try { //领取金币
                let 领50金币 = id('bei').findOne(500)
                if (领50金币) {
                    click_button(领50金币.bounds())
                    toastLog("1")
                }
            } catch (e) { }

            try { //领取金币
                let 立即更新 = text('立即更新').findOne(500)
                if (立即更新) {
                    关闭按钮 = 立即更新.parent().child(2)
                    关闭按钮.click()
                    toastLog("2")
                }
            } catch (e) { }

        }
        thread.interrupt();
    });
}

app_func.main = function () {
    console.log("start...");
    var open_app = launchAppEnhance(app_func.appName);
    //多了一个 快7发红包弹窗   立即登录  id("open_red_packet")

    if (open_app) {
        sleep(app_func.sleepTime)
        toastLog("启动成功")
        thread_handle()
        //预处理 初始化 各种常用按钮坐标  签到后变  任务
        if (find_task_button("去签到") < 0 && find_task_button("任务") < 0) {
            toastLog("寻找任务按钮失败")
            return -1
        }
        init_taskinfo()

        var taskList =
            [
                "handle_sign_task",
                "open_baoxiang",
                "handle_watch_ad_task",
                // "yaoshu_task",
                "sleep_task",
                "lingjinbi",
                "handle_watch_video_task",
            ]
        //  "sleep_task",
        //签到任务
        //看广告赚金币
        run_task(taskList)

        toastLog("任务已执行完毕")
    }
    else {
        console.log("app启动失败");
    }

    console.log("end...");
    app_func.taskEnd = true
}

events.on("exit", function () {
    if (app_func.finish) {
        onexit()
    }
    else {
        onerror();
    }
});

try {
    app_func.main();
    app_func.finish = true
} catch (error) {
    toastLog(error);
}

//收益统计部分--------------------------

//任务顺序:   1   2   3    4   5   6   7
function init_taskinfo() {
    console.log("初始化任务数据")
    //for test  删除
    storages.remove(app_func.appName)


    //先获取
    var storage = storages.create(app_func.appName)
    var storage2 = storages.create("xiangxiangyuedu");
    app_func.storage = storage
    taskInfo = storage.get(app_func.appName)
    console.log(taskInfo)
    app_func.startTime = new Date().getTime()   //脚本启动时间

    if (taskInfo == null) {
        toastLog("任务信息未初始化")
        var phone = device.model
        var phoneid = storage2.get("imei")
        taskInfo = {
            appName: app_func.appName,
            手机型号: phone,
            手机标识: phoneid,
            任务列表: [0, 1, 2, 3, 4, 5, 6],
            任务信息: [

            ],
            当天执行次数: 0,
            当天执行完成次数: 0,
            当天执行中断次数: 0,
            单次运行时间记录: [],
            当天总耗时: 0
        }

    }
    console.log("taskInfo:", taskInfo)
    app_func.taskInfo = taskInfo

    return 0
}

function get_account_coin(index) {
    //进入福利页面
    // var coin = -1
    // trytimes = 3
    // while( coin < 0 ){
    //     trytimes--
    //     if( trytimes == 0 ){
    //         break
    //     }
    //     clean_obs()
    //     if( app_func.bounds.task_button ){
    //         click_button( app_func.bounds.task_button )
    //         if( index == 0){
    //             sleep(5000)
    //             handle_more_reward_task()  //针对自动签到的app
    //         } 

    //         //还有个版本是金币余额
    //         var 金币收益 = null
    //         if( textStartsWith( "金币余额").exists() ){
    //             金币收益 = auto_find_button("金币余额")
    //             if( 金币收益 ){
    //                 num= 金币收益.text().replace(/[^0-9]/ig,"");
    //                 coin = num;
    //             }

    //         }
    //         else if( textStartsWith( "我的金币").exists() ){
    //             金币收益 = auto_find_button("我的金币")
    //             if( 金币收益 ){
    //                 target = 金币收益.parent().child(0)
    //                 coin = parseInt( target.text() );
    //             }
    //         }

    //     }
    //     else{
    //         console.log( "没有初始化按钮" )
    //     }
    // }

    return 0
}

//获取账户金额
function get_account_money() {
    return 0
}

function excFunction(name) {
    //确保callback是一个函数   
    var callback = name + "()"
    return eval(callback);
}

function run_function(functionName, Index) {
    var tmpInfo =
    {
        taskIndex: Index,      //任务编号
        funcName: functionName,        //执行函数名
        useTime: 0,           //消耗时间
        BeginCoin: 0,         //任务运行前金币
        EndCoin: 0,            //任务运行后金币
        getCoin: 0,            //获得金币
        BeginMoney: 0,         //任务运行前金钱
        EndMoney: 0,           //任务运行后金钱
        getMoney: 0,           //获得金钱
        result: 0,            //0成功 -1失败
        recordTime: 0,        //记录时间
    }
    //执行前记录  coin  money 执行后再获取一次 得到金币的变化 就是收益

    var tmpcoin = 0
    var tmpmoney = 0
    if (Index == 0) {
        tmpcoin = get_account_coin()
        tmpmoney = get_account_money()
        app_func.coin = tmpcoin
        console.log("初始金币数" + tmpcoin)
    }  //第一个任务记录金币起始数量，
    else {
        tmpcoin = app_func.coin
        tmpmoney = get_account_money()
    }

    var startTime = new Date().getTime();   //时间戳

    //执行函数
    var result = excFunction(functionName);
    if (result < 0) {
        console.log(functionName + "执行失败")
        clean_obs()
    }

    //执行后
    endTime = new Date().getTime()
    var useTime = (endTime - startTime) / 1000
    var nowcoin = get_account_coin()
    for (var i = 0; i < 2; i++) {
        if (nowcoin < tmpcoin) {   //重新获取下
            console.log("金币数获取异常，重新获取" + nowcoin + "-" + tmpcoin)
            nowcoin = get_account_coin()
        }
        else {
            break;
        }
    }

    var coin = nowcoin - tmpcoin
    app_func.coin = nowcoin
    var money = get_account_money() - tmpmoney

    tmpInfo.useTime = useTime
    tmpInfo.BeginCoin = tmpcoin
    tmpInfo.EndCoin = nowcoin
    tmpInfo.getCoin = coin
    tmpInfo.BeginMoney = tmpcoin
    tmpInfo.EndMoney = nowcoin
    tmpInfo.getMoney = money
    tmpInfo.result = result
    tmpInfo.recordTime = endTime

    if (app_func.taskInfo) {
        app_func.taskInfo.任务信息.push(tmpInfo)
    }

    return 0
}

/**
 * 执行任务列表函数
 * @param {当前APP可执行的任务名列表} taskNameList
 */
function run_task(taskNameList) {
    //本地文件记录的 应做任务列表
    任务列表 = app_func.taskInfo.任务列表

    执行任务数 = Math.min(taskNameList.length, 任务列表.length)
    console.log("执行任务数:", 执行任务数)
    if (taskNameList.length <= 0 || 任务列表.length <= 0) {
        toastLog("任务数量为0")
        return -1
    }

    for (var i = 0; i < 执行任务数; i++) {
        console.log("开始执行任务:" + taskNameList[任务列表[i]])
        run_function(taskNameList[任务列表[i]], 任务列表[i])
    }

    return 0
}

//异常退出 后续操作
function onerror() {
    if (app_func.taskInfo) {
        当前时间 = new Date().getTime()
        本次任务耗时 = (当前时间 - app_func.startTime) / 1000
        app_func.taskInfo.当天执行次数 = app_func.taskInfo.当天执行次数 + 1
        app_func.taskInfo.当天执行中断次数 = app_func.taskInfo.当天执行中断次数 + 1
        var tmpdata = {
            开始记录时间: app_func.startTime,
            结束记录时间: 当前时间,
            本次任务耗时: 本次任务耗时,
            当天执行次序: app_func.taskInfo.单次运行时间记录.length + 1
        }
        app_func.taskInfo.单次运行时间记录.push(tmpdata)
        app_func.taskInfo.当天总耗时 = app_func.taskInfo.当天总耗时 + 本次任务耗时
        app_func.storage.put(app_func.appName, app_func.taskInfo)
        console.log(app_func.taskInfo)
    }
    else {
        console.log("没有任务信息")
    }
}
//正常退出 后续操作
function onexit() {
    if (app_func.taskInfo) {
        当前时间 = new Date().getTime()
        本次任务耗时 = (当前时间 - app_func.startTime) / 1000
        app_func.taskInfo.当天执行次数 = app_func.taskInfo.当天执行次数 + 1
        app_func.taskInfo.当天执行完成次数 = app_func.taskInfo.当天执行完成次数 + 1
        var tmpdata = {
            开始记录时间: app_func.startTime,
            结束记录时间: 当前时间,
            本次任务耗时: 本次任务耗时,
            当天执行次序: app_func.taskInfo.单次运行时间记录.length + 1
        }
        app_func.taskInfo.单次运行时间记录.push(tmpdata)
        app_func.taskInfo.当天总耗时 = app_func.taskInfo.当天总耗时 + 本次任务耗时
        app_func.storage.put(app_func.appName, app_func.taskInfo)
        console.log(app_func.taskInfo)
    }
    else {
        console.log("没有任务信息")
    }
}

var storage = storages.create("xiangxiangyuedu");
storage.put("script_running_status", "end");